package com.swiftride.mq.customer;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.swiftride.constants.Constants;
import com.swiftride.pojo.domain.Order;
import com.swiftride.service.IOrderService;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

@Component
@RocketMQMessageListener(
        topic = Constants.RocketMQ.ORDER_TIMEOUT_CANCEL_TOPIC,
        selectorExpression = Constants.RocketMQ.ORDER_TIMEOUT_CANCEL_TAG,
        consumerGroup = Constants.RocketMQ.ORDER_TIMEOUT_CANCEL_GROUP,
        messageModel = MessageModel.CLUSTERING
)
public class CustomerOrderDelayCancel implements RocketMQListener<MessageExt> {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        String orderNo = new String(body, StandardCharsets.UTF_8);
        Order order = orderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNo, orderNo));
        if (ObjectUtil.isNotNull(order) && order.getStatus().equals(Constants.Order.WAIT_ORDER)) {
            //订单超时,自动取消,删除redis中的订单
            //3.1 删除redis中的订单
            String order2RedisKey = String.format(Constants.Redis.ORDER_INFO_KEY, orderNo);
            redisTemplate.delete(order2RedisKey);
            //3.2 修改订单状态
            order.setStatus(Constants.Order.CUSTOMER_CANCEL);
            order.setUpdateTime(new Date());
            orderService.updateById(order);
        }
    }
}
